package com.youkeda.app.service.impl;

import com.youkeda.app.dao.PreSingleRedEnvelopeDao;
import com.youkeda.app.dataobject.PreSingleRedEnvelopeDO;
import com.youkeda.app.model.PreSingleRedEnvelope;
import com.youkeda.app.params.BatchAddPreSingleRedEnvelopeParam;
import com.youkeda.app.service.PreSingleRedEnvelopeService;
import com.youkeda.app.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName PreSingleRedEnvelopeServiceImpl
 * @Author 刘正星
 * @Date 2020/9/2 18:52
 **/
@Service
public class PreSingleRedEnvelopeServiceImpl implements PreSingleRedEnvelopeService {

    @Autowired
    private PreSingleRedEnvelopeDao preSingleRedEnvelopeDao;

    @Override
    public PreSingleRedEnvelope save(PreSingleRedEnvelope redEnvelope) {
        if (redEnvelope == null) {
            return null;
        }


        if (StringUtils.isEmpty(redEnvelope.getId())) {

            PreSingleRedEnvelopeDO redEnvelopeDO = new PreSingleRedEnvelopeDO(redEnvelope);
            redEnvelopeDO.setId(UUIDUtils.getUUID());

            int insertSize = preSingleRedEnvelopeDao.insert(redEnvelopeDO);
            if (insertSize<1){
                return null;
            }
            redEnvelope.setId(redEnvelopeDO.getId());
        }

        PreSingleRedEnvelopeDO redEnvelopeDO = new PreSingleRedEnvelopeDO(redEnvelope);
        int insertSize = preSingleRedEnvelopeDao.insert(redEnvelopeDO);
        if (insertSize < 1){
            return null;
        }

        return redEnvelope;

    }

    @Override
    public List<PreSingleRedEnvelope> batchAdd(BatchAddPreSingleRedEnvelopeParam batchAddPreSingleRedEnvelopeParam) {
        if (batchAddPreSingleRedEnvelopeParam == null) {
            return null;
        }

        List<PreSingleRedEnvelopeDO> preSingleRedEnvelopeDOList = batchAddPreSingleRedEnvelopeParam.getPreSingleRedEnvelopeList()
                .stream().map(redEnvelope -> {
                   PreSingleRedEnvelopeDO preSingleRedEnvelopeDO = new PreSingleRedEnvelopeDO(redEnvelope);
                   if (StringUtils.isEmpty(preSingleRedEnvelopeDO.getId())){
                       preSingleRedEnvelopeDO.setId(UUIDUtils.getUUID());
                   }
                   return preSingleRedEnvelopeDO;
                }).collect(Collectors.toList());
        //preSingleRedEnvelopeDOList.forEach(e ->System.out.print(e.getId()));

        preSingleRedEnvelopeDao.batchAdd(preSingleRedEnvelopeDOList);
        return batchAddPreSingleRedEnvelopeParam.getPreSingleRedEnvelopeList();
    }
}
